/**
 * 
 */
package com.ifast.common.utils.alioss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.google.common.collect.Maps;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

/** 
 * 项目名称：afast
 * 类名称：OssCommClientUtil
 * 类描述： 
 * 创建人：Administrator 
 * 创建时间：2017年6月16日 上午9:11:10
 * 修改人：Administrator 
 * 修改时间：2017年6月16日 上午9:11:10
 * 修改备注： 
 * @version 
 */
@Slf4j
public class OssCommClientUtil {

	private static OssCommClientUtil instance;

	@Value("${ossimg}")
	private String ossimg;
	
	public static OssCommClientUtil getInstance() {
		synchronized (OssCommClientUtil.class) {
			if (OssCommClientUtil.instance == null){
				instance = new OssCommClientUtil();
			}
			return instance;
		}
	}

	/**
	 * @Title:           uploadImg2OssMorePic
	 * @Description:     多图上传图片
	 * @param:           @param request
	 * @param:           @param basePath       路径
	 * @param:           @param bluckName      阿里云磁盘名称
	 * @param:           @param ossClient	       阿里云连接对象
	 * @param:           @param decssPicFlag   图片压缩标识
	 * @param:           @return   
	 * @return:          UploadResult   
	 * @throws
	 */
	public UploadResult uploadImg2OssMorePic(HttpServletRequest request,
                                             String basePath, String bluckName, OSSClient ossClient, boolean decssPicFlag, String style) {
		UploadResult result = new UploadResult();
		// 解析器解析request的上下文
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 先判断request中是否包涵multipart类型的数据，
		if (multipartResolver.isMultipart(request)) {
			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next());
				log.info("开始");
				if (file == null) {
					result.setSuccess(false);
					result.setMessage("文件上传失败，文件内容为空！");
					return result;
				}
				if (file.getSize() > ossConst.MAXSIZE* 1024 * 1024 ) {
					String originalFilename = file.getOriginalFilename();
					result.setSuccess(false);
					result.setMessage("文件上传失败，文件"+originalFilename+"超过100M！");
					return result;
				}
				instance.uploadImg2OssOnePic(result, file, basePath,bluckName,ossClient,decssPicFlag,style);
			}
		}
		//关闭客户端
		ossClient.shutdown();
		return result;
	}
	
	// 单图上传图片
	private UploadResult uploadImg2OssOnePic(UploadResult uploadResult,
                                             MultipartFile file, String basePath, String bluckName, OSSClient ossClient, boolean decssPicFlag, String style) {
		String originalFilename = file.getOriginalFilename();
		log.info("附件上传" + originalFilename);
		String substring = originalFilename.substring(
				originalFilename.lastIndexOf('.')).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis()
				+ substring;
		try {
			InputStream inputStream = file.getInputStream();
			Map<String,String> maps =  instance.uploadFile2OSSForStream(inputStream, name,
					basePath,"pic",bluckName,ossClient);
			String md5 = maps.get("ret");
			String url = maps.get("url");
			log.info("--------------------文件上传开始uploadImg2OssOnePic="+url);
			log.info("--------------------文件上传开始uploadImg2OssOnePic="+md5);
			if (StrUtil.isBlank(md5)) {
				uploadResult.setSuccess(false);
				uploadResult.setMessage("图片上传失败！");
				return uploadResult;
			}
			// 获取回掉地址
			String returnUrl = instance.getUrl(url,bluckName,ossClient,decssPicFlag,style);
			
			//文件请求地址和文件大小
			Map<String,Object> urlAndSize = Maps.newHashMap();
			urlAndSize.put(returnUrl,file.getSize());
			uploadResult.getUrlAndSize().add(urlAndSize);
			
			uploadResult.getFileURLs().add(returnUrl);
		} catch (Exception e) {
			uploadResult.setSuccess(false);
			uploadResult.setMessage("图片上传失败！");
			uploadResult.getFileURLs().clear();
			log.error("图片上传失败！" + e.toString());
		}
		return uploadResult;
	}
	
	

	/**
	 * 上传到OSS服务器 如果同名文件会覆盖服务器上的
	 *
	 * @param instream
	 *            文件流
	 * @param fileName
	 *            文件名称 包括后缀名
	 * @return 出错返回"" ,唯一MD5数字签名
	 */
	public Map<String,String> uploadFile2OSSForStream(InputStream instream, String fileName,
                                                      String basePath, String laiyuan, String bluckName, OSSClient ossClient) {
		//设置acl
		Map<String,String> maps = Maps.newHashMap();
		try {
			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(instream.available());
			objectMetadata.setCacheControl("max-age=86400");
			objectMetadata.setHeader("Pragma", "cache");
			String tou = getContentType(fileName.substring(fileName.lastIndexOf('.')));
			if(StrUtil.isNotBlank(tou)){
				objectMetadata.setContentType(tou);
				objectMetadata.setContentDisposition("inline;filename=" + fileName);
				// 上传文件
				String saveUrl = UploadUtils.createSaveURLAli(basePath)+"/";
				PutObjectResult putResult;
				if("pic".equals(laiyuan)){
					putResult = ossClient.putObject(bluckName, saveUrl+fileName , instream);
				}else{
					putResult = ossClient.putObject(new PutObjectRequest(bluckName, saveUrl
							+ fileName , instream, objectMetadata).<PutObjectRequest>withProgressListener(new GetProgressUtil.PutObjectProgressListener()));
				}
				String ret = putResult.getETag();
				maps.put("url", saveUrl+fileName);
				maps.put("ret", ret);
			}
		}catch(OSSException e){
			log.error(e.getMessage(), e);
		}catch (ClientException | IOException ce) {
			log.error(ce.getMessage(), ce);
		} finally {
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		}
		return maps;
	}

	/**
	 * 上传到OSS服务器 如果同名文件会覆盖服务器上的
	 * @param content
	 *            字节流
	 * @param fileName
	 *            文件名称 包括后缀名
	 * @return 出错返回"" ,唯一MD5数字签名
	 */
	public Map<String,String> uploadFile2OSSForByte(byte[] content, String fileName,
                                                    String basePath, String laiyuan, String bluckName, OSSClient ossClient) {
		//设置acl
		Map<String,String> maps = Maps.newHashMap();
		try {
			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setCacheControl("max-age=86400");
			objectMetadata.setContentLength(content.length);
			objectMetadata.setHeader("Pragma", "cache");
			String tou = getContentType(fileName.substring(fileName.lastIndexOf('.')));
			if(StrUtil.isNotBlank(tou)){
				objectMetadata.setContentType(tou);
				objectMetadata.setContentDisposition("inline;filename=" + fileName);
				// 上传文件
				String saveUrl = UploadUtils.createSaveURLAli(basePath)+"/";
				PutObjectResult putResult;
				if("pic".equals(laiyuan)){
					putResult = ossClient.putObject(bluckName, saveUrl+fileName , new ByteArrayInputStream(content));
					String ret = putResult.getETag();
					maps.put("url", saveUrl+fileName);
					maps.put("ret", ret);
				}else{
					maps.put("url", "");
					maps.put("ret", "");
				}
			}
		}catch(OSSException e){
			log.error(e.getMessage(), e);
		}catch (ClientException ce) {
			log.error(ce.getMessage(), ce);
		}
		return maps;
	}
	
	// 上传文件
	public UploadResult uploadImg2OssMoreFile(HttpServletRequest request,
                                              String basePath, String bluckName, OSSClient ossClient) {
		UploadResult result = new UploadResult();
		// 解析器解析request的上下文
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 先判断request中是否包涵multipart类型的数据，
		if (multipartResolver.isMultipart(request)) {
			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					instance.uploadImg2OssOneFile(result, file, basePath,bluckName,ossClient);
				}
			}
		}
		ossClient.shutdown();
		return result;
	}

	// 上传文件
	private UploadResult uploadImg2OssOneFile(UploadResult uploadResult,
                                              MultipartFile file, String basePath, String bluckName, OSSClient ossClient) {
		if (file.getSize() > 1024 * 1024 * 100) {
			uploadResult.setSuccess(false);
			uploadResult.setMessage("上传文件大小不能超过100M！");
			return uploadResult;
		}
		String originalFilename = file.getOriginalFilename();
		String substring = originalFilename.substring(
				originalFilename.lastIndexOf(".")).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis()
				+ substring;
		try {
			InputStream inputStream = file.getInputStream();
			Map<String,String> maps =  instance.uploadFile2OSSForStream(inputStream, name,
					basePath,"file",bluckName,ossClient);
			String md5 = maps.get("ret");
			String url = maps.get("url");
			if (StrUtil.isBlank(md5)) {
				uploadResult.setSuccess(false);
				uploadResult.setMessage("上传失败！");
				return uploadResult;
			}
			// 获取回掉地址
			String returnUrl = instance.getUrlFile(url,bluckName,ossClient);
			uploadResult.getFileURLs().add(returnUrl);
		} catch (Exception e) {
			uploadResult.setSuccess(false);
			uploadResult.setMessage("上传失败！");
			uploadResult.getFileURLs().clear();
			log.error("上传失败！" + e.toString());
			log.error(e.getMessage(), e);
		}
		return uploadResult;
	}
	
	//网络文件
	public UploadResult uploadFile2OSSFromNetOneFile(InputStream instream, String fileName,
                                                     String basePath, String laiyuan, String urlz, String bluckName, OSSClient ossClient) {
		UploadResult uploadResult = new UploadResult();
		try {
			instream = new URL(urlz).openStream();
			String saveUrl = UploadUtils.createSaveURLAli(basePath)+"/";
			PutObjectResult putResult =  null;
			if("pic".equals(laiyuan)){
				// 带进度条的上传 
				putResult =  ossClient.putObject(new PutObjectRequest(bluckName, RandomUtil.randomUUID(), instream).<PutObjectRequest>withProgressListener(new GetProgressUtil.PutObjectProgressListener()));
			}else{
				putResult =  ossClient.putObject(new PutObjectRequest(bluckName, RandomUtil.randomUUID(), instream).
	                    <PutObjectRequest>withProgressListener(new GetProgressUtil.PutObjectProgressListener()));
			}
			String ret = putResult.getETag();
			if (StrUtil.isBlank(ret)) {
				uploadResult.setSuccess(false);
				uploadResult.setMessage("上传失败！");
				return uploadResult;
			}
			if("pic".equals(laiyuan)){
				// 获取回掉地址
				String returnUrl = instance.getUrl(saveUrl+fileName,bluckName,ossClient,true,"");
				uploadResult.getFileURLs().add(returnUrl);
			}else{
				// 获取回掉地址
				String returnUrl = instance.getUrlFile(saveUrl+fileName,bluckName,ossClient);
				uploadResult.getFileURLs().add(returnUrl);
			}
		}catch(OSSException e){
			log.error(e.getMessage(), e);
		}catch (ClientException ce) {
			log.error(ce.getMessage(), ce);
		}catch (IOException e) {
			log.error(e.getMessage(), e);
			uploadResult.setSuccess(false);
			uploadResult.setMessage("上传失败！");
		} finally {
			ossClient.shutdown();
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		}
		return uploadResult;
	}

	public UploadResult deletePic(String url, String bluckName, OSSClient ossClient) {
		UploadResult result = new UploadResult();
		try {
			if(StringUtils.isNotBlank(url)){ 
				log.info("--------------------删除成功deletePic=" + url);
				ossClient.deleteObject(bluckName,StringUtils.substringBetween(url, ".com/","?"));  
			} 
		} catch (Exception e) { 
			result.setSuccess(false);
			result.setMessage("删除失败");
			log.info("--------------------删除失败deletePic=" + e.getMessage());
		} 
		ossClient.shutdown();
		return result;
	}
	/**
	 * 获得url链接
	 *
	 * @param key
	 * @return
	 */
	public String getUrl(String key, String bluckName, OSSClient ossClient, boolean decssPicFlag, String style) {
		// 设置URL过期时间为10年 3600l* 1000*24*365*10
		Date expiration = new Date(System.currentTimeMillis()+ 3600L  * 1000 * 24
				* 365 * 10);
		GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bluckName, key, HttpMethod.GET);
	    req.setExpiration(expiration);
	    //开启图片压缩
	    if(StrUtil.isBlank(style)){
	    	style = ossimg;
	    }
	    if(decssPicFlag){
	       req.setProcess(style);
	    }
		// 生成URL
		URL url = ossClient.generatePresignedUrl(req);
		if (url != null) {
			return url.toString();
		}
		return null;
	}
	
	public String getUrlFile(String key, String bluckName, OSSClient ossClient) {
		// 设置URL过期时间为10年 3600l* 1000*24*365*10
		Date expiration = new Date(System.currentTimeMillis()+ 3600L * 1000 * 24
				* 365 * 10);
		// 生成URL
		URL url = ossClient.generatePresignedUrl(bluckName,key,expiration);
		if (url != null) {
			return url.toString();
		}
		return null;
	}
		
	

	/**
	 * Description: 判断OSS服务文件上传时文件的contentType
	 *
	 * @param FilenameExtension
	 *            文件后缀
	 * @return String
	 */
	public static String getContentType(String FilenameExtension) {
		if (FilenameExtension.equalsIgnoreCase(".bmp")) {
			return "image/bmp";
		}
		if (FilenameExtension.equalsIgnoreCase(".gif")) {
			return "image/gif";
		}
		if (FilenameExtension.equalsIgnoreCase(".jpeg")
				|| FilenameExtension.equalsIgnoreCase(".jpg")
				|| FilenameExtension.equalsIgnoreCase(".png")) {
			return "image/jpeg";
		}
		if (FilenameExtension.equalsIgnoreCase(".html")) {
			return "text/html";
		}
		if (FilenameExtension.equalsIgnoreCase(".txt")) {
			return "text/plain";
		}
		if (FilenameExtension.equalsIgnoreCase(".vsd")) {
			return "application/vnd.visio";
		}
		if (FilenameExtension.equalsIgnoreCase(".pptx")
				|| FilenameExtension.equalsIgnoreCase(".ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (FilenameExtension.equalsIgnoreCase(".docx")
				|| FilenameExtension.equalsIgnoreCase(".doc")) {
			return "application/msword";
		}
		if (FilenameExtension.equalsIgnoreCase("xml")) {
			return "text/xml";
		}
		if (FilenameExtension.equalsIgnoreCase(".mpeg4")) {
			return "video/mpeg4";
		}
		if (FilenameExtension.equalsIgnoreCase(".mp4")) {
			return "video/mp4";
		}
		if (FilenameExtension.equalsIgnoreCase(".avi")) {
			return "video/avi";
		}
		if (FilenameExtension.equalsIgnoreCase(".mpv")) {
			return "video/mpg";
		}
		if (FilenameExtension.equalsIgnoreCase(".flv")) {
			return "video/x-flv";
		}
		return "";
	}
}
